package com.ds.smartstudio.handler;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ds.smartstudio.config.MyMQTTCallback;
import com.ds.smartstudio.controller.WebSocket;
import com.ds.smartstudio.entity.Device;
import com.ds.smartstudio.entity.History;
import com.ds.smartstudio.entity.Type;
import com.ds.smartstudio.service.BO.DeviceMqttMessage;
import com.ds.smartstudio.service.DeviceService;
import com.ds.smartstudio.service.HistoryService;
import com.ds.smartstudio.service.TypeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class MqttMessageHandler {
    private static HistoryService staticHistoryService;

    private static TypeService staticTypeService;

    private static DeviceService staticDeviceService;

    private static WebSocket staticWebSocket;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private TypeService typeService;
    @Autowired
    private WebSocket webSocket;
    @PostConstruct
    public void init() {
        staticHistoryService = historyService;
        staticDeviceService = deviceService;
        staticTypeService = typeService;
        staticWebSocket = webSocket;
    }
    public static void receive(String topic, String msg) {
        DeviceMqttMessage device = null;
        String[] split = topic.split("/");
        if (msg.equals("-1")) {
            History history = new History();
            history.setDsDeviceMac(split[1]);
            history.setDsHistoryValue("-1");
            staticHistoryService.save(history);
        } else if (msg.startsWith("{") && msg.endsWith("}")) {
            JSONObject deviceMsg = JSON.parseObject(msg);
            JSONObject deviceJson = deviceMsg.getJSONObject("deviceMqttMessage");
            JSONArray sensors = deviceJson.getJSONArray("sensors");
            for (int i = 0; i < sensors.size(); i++) {
                JSONObject sensor = sensors.getJSONObject(i);
                sensor.put("timestamp", new Date());
            }
            deviceJson.put("sensors", sensors);
            device = deviceJson.toJavaObject(DeviceMqttMessage.class);
            MqttMessageHandler.historySave(device);
        }
    }

    public static boolean historySave(DeviceMqttMessage deviceMqttMessage) {
        boolean flag = false;
        try {
            if (deviceMqttMessage != null) {
                addDevice(deviceMqttMessage);
                List<String> macs = staticDeviceService.macs();
                List<Type> types = staticTypeService.list();
                if (macs.contains(deviceMqttMessage.getMac())) {
                    for (int i = 0; i < deviceMqttMessage.getSensors().size(); i++) {
                        History history = new History();
                        StringBuilder value = new StringBuilder(deviceMqttMessage.getSensors().get(i).getValue());
                        String type = deviceMqttMessage.getSensors().get(i).getType();
                        if (type.equals("switch")) {
                            if (value.toString().equals("1")) {
                                value.setLength(0);
                                value.append("开");
                            } else if (value.toString().equals("0")) {
                                value.setLength(0);
                                value.append("关");
                            }
                        } else {
                            for (Type type1 : types) {
                                if (type1.getDsTypeName().equals(type)) {
                                    value.append(type1.getDsTypeSuffix());
                                    break;
                                }
                            }
                        }

                        history.setDsHistoryValue(value.toString());
                        history.setCreateTime(deviceMqttMessage.getSensors().get(i).getTimestamp());
                        history.setDsDeviceMac(deviceMqttMessage.getMac());
                        staticHistoryService.save(history);
                        staticWebSocket.sendAllMessage(JSON.toJSONString(history));
                        flag = true;
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.toString());
        }
        return flag;
    }

    public static void addDevice(DeviceMqttMessage deviceMqttMessage) {
        List<String> macs = staticDeviceService.macs();
        if (!macs.contains(deviceMqttMessage.getMac())) {
            Device device = new Device();
            device.setDsDeviceMac(deviceMqttMessage.getMac());
            device.setDsDeviceStatus(0);
            device.setDsDeviceFirmware(deviceMqttMessage.getVersion());
            device.setDsDeviceModel(deviceMqttMessage.getModel());
            staticDeviceService.save(device);
        }
    }
}
